import React from 'react';
import cn from 'classnames';
import { Icon, Badge, message } from 'antd';
import { Link }  from 'umi';
import { connect } from 'umi';

import authHelper from '@/utils/auth/helper';
import pageTabUtil from '@/utils/pageTabUtil';
import { getMenuMatches } from '@/components/SiderMenu/SiderMenuUtils';
import { urlToList } from '@/components/_utils/pathTools';
import { eventTrack } from '@/utils/track';
import { withRouter } from 'umi';

import excludePath from './exclude.config';
import styles from './SubMenu.less';

const colorList = [
    '#FFA808',
    '#5B8FF9',
    '#5BD8A6',
    '#5E7092',
    '#E8694A',
    '#6DC8EC',
    '#9270CA',
    '#FE914B',
    '#279A99',
    '#FF99C3'
];

const getSelectedMenuKeys = (pathname, flatMenuKeys) =>
    urlToList(pathname).map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop());

const getcolor = index => colorList[index % colorList.length];

const eventTrackHandler = path => {
    const eventMap = {
        '/personal/message/system/remind': {
            eventName: 'personal_message_system_remind_click',
            pageName: 'personal_message_system_remind'
        },
        '/personal/message/system/notice': {
            eventName: 'personal_message_system_notice_click',
            pageName: 'personal_message_system_remind'
        },
        '/office/institutions/rulesManage/personnel': {
            eventName: 'institutions_rules_manage_personnel_click',
            pageName: 'institutions_rules_manage'
        },
        '/office/institutions/rulesManage/finance': {
            eventName: 'institutions_rules_manage_finance_click',
            pageName: 'institutions_rules_manage'
        },
        '/office/institutions/rulesManage/brand': {
            eventName: 'institutions_rules_manage_brand_click',
            pageName: 'institutions_rules_manage'
        },
        '/office/personnelManagement/recruitment/demand/list': {
            eventName: 'personnel_management_recruitment_demand_list_click',
            pageName: 'personnel_management_recruitment'
        },
        '/office/personnelManagement/recruitment/setting': {
            eventName: 'personnel_management_recruitment_setting_click',
            pageName: 'personnel_management_recruitment'
        }
    };
    const eventParam = eventMap[path];
    if (eventParam) {
        eventTrack(eventParam);
    }
};

const SubMenu = ({ menu, global, location, path }) => {
    // 不再使用当前路由，而改用当前页签的tabKey
    const currentPath = pageTabUtil.getCurrentPath();
    const { noticeCount = 0, taskCount } = global;
    const {
        toExecuteTaskNum = 0,
        toAuditTaskNum = 0,
        toAcceptTaskNum = 0,
        toScoreTaskNum = 0,
        toEstimateTaskNum = 0
    } = taskCount;
    const { pathname } = location;

    // 不同模块跳转时，特定路由菜单隐藏
    if (excludePath.includes(path)) {
        return null;
    }

    // 使用menu的model
    const { breadcrumbNameMap } = menu;
    const menuItem = breadcrumbNameMap[currentPath] || { parent: {} };
    // 获取当前路由的配置信息
    const currentRoute = breadcrumbNameMap[pathname];

    // 只有4级菜单才显示
    // 添加hideInSubMenu控制是否显示4级菜单
    if (menuItem.level < 3 || currentRoute?.hideInSubMenu === true) {
        return null;
    }

    // 其实还有5级😂
    let menuData = menuItem.parent.children || [];
    if (menuItem.level === 4) {
        menuData = breadcrumbNameMap[menuItem.parent.path].parent.children || [];
    }

    // 四级菜单选中
    const selectedMenuKeys = getSelectedMenuKeys(currentPath, Object.keys(breadcrumbNameMap));

    const displayMenu = menuData
        .filter(item => !item.hideInMenu && authHelper.checkCode(item.code))
        .map(item => ({
            ...item,
            originPath: item.path,
            path: authHelper.getActualPath(item.path)
        }));

    const renderIcon = (item, index) => {
        const iconStyle = { color: getcolor(index), marginRight: 4 };
        if (item.iconType) {
            return <Icon type={item.iconType} theme="filled" style={iconStyle} />;
        }
        if (item.iconfont) {
            return <i className={`icon iconfont ${item.iconfont}`} style={iconStyle} />;
        }
        return null;
    };

    const getLinkProps = item => {
        if (item.path) {
            return {
                to: { pathname: item.path, state: { tabRoute: true, tabRefresh: true } }
            };
        }
        return {
            onClick: () => {
                message.error('检测到无对应权限，请确认权限配置！');
            }
        };
    };

    const renderLinkItem = (item, index) => {
        const linkProps = getLinkProps(item);
        const button = (
            <Link
                className={cn(styles.button, {
                    [styles.selected]: selectedMenuKeys.includes(item.originPath) // 判断上下级时用originPath
                })}
                key={item.path}
                onClick={() => {
                    eventTrackHandler(item.path);
                }}
                {...linkProps}
            >
                {renderIcon(item, index)}
                {item.name}
            </Link>
        );
        const badgeProps = {
            style: { width: 8, height: 8 },
            offset: [-12, 1],
            key: item.path
        };
        if (item.path === '/personal/message/system/notice') {
            return (
                <Badge dot={noticeCount > 0} {...badgeProps}>
                    {button}
                </Badge>
            );
        }
        if (item.path === '/work/task/mytask/execute') {
            return (
                <Badge dot={toExecuteTaskNum > 0} {...badgeProps}>
                    {button}
                </Badge>
            );
        }
        if (item.path === '/work/task/mytask/audit') {
            return (
                <Badge dot={toAuditTaskNum > 0} {...badgeProps}>
                    {button}
                </Badge>
            );
        }
        if (item.path === '/work/task/mytask/acceptance') {
            return (
                <Badge dot={toAcceptTaskNum > 0} {...badgeProps}>
                    {button}
                </Badge>
            );
        }
        if (item.path === '/work/task/mytask/score') {
            return (
                <Badge dot={toScoreTaskNum > 0} {...badgeProps}>
                    {button}
                </Badge>
            );
        }
        if (item.path === '/work/task/mytask/assessment') {
            return (
                <Badge dot={toEstimateTaskNum > 0} {...badgeProps}>
                    {button}
                </Badge>
            );
        }
        return button;
    };
    return path === pathname && displayMenu?.length > 0 ? (
        <div className={displayMenu?.length > 0 ? styles.container : ''}>
            {displayMenu.map((item, index) => renderLinkItem(item, index))}
        </div>
    ) : null;
};

export default React.memo(
    withRouter(
        connect(({ menu, global }) => ({
            menu,
            global
        }))(SubMenu)
    )
);
